package com.fr.chicken.pay.com.shb.pay.main;

import com.fr.chicken.manager.recharge.RechargeManager;
import com.fr.chicken.pay.com.shb.pay.util.HttpUtils;
import com.fr.chicken.pay.com.shb.pay.util.RSAUtils;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;

import java.text.SimpleDateFormat;
import java.util.Date;
@Repository
public class Payment {
    /**
     * 下单
     * 请求数据 {"businessContext":{"merchantNumber":"API0100002802000031","subMerchantNumber":"","merchantOrderNumber":"dsorderid2018011514","tradeAmount":"1","currenciesType":"CNY","commodityBody":"商品详情","channelMapped":"SAND_PAY","defrayalType":"ALI_NATIVE","userId":"123","returnUrl":"www.baidu.com","notifyUrl":"www.baidu.com"},"businessHead":{"charset":"00","version":"V1.0.0","method":"payment","merchantNumber":"API0100002802000031","requestTime":"20180115180101","signType":"","sign":""}}
     * 响应数据 {"businessContext":{"shbOrderNumber":"API01180115180103001214000028"},"businessHead":{"charset":"UTF-8","merchantNumber":"API0100002802000031","method":"payment","responseTime":"20180115180122","signType":"RSA","version":"V1.0.0","sign":"C98kfJo422jPsbwcsNCazfEXSVs3RPSwVfWqmGJl7owq1NwvD8e/OHr4PLz57dwNH/7eEG6hxio/hEZBGdsbAP6ISf39W4p7Tt7Wkca6w78v1QDpsQiNauI118Bl01eL6BB1pCn8OwYSUJ+2LQ9cMcMOdjpM46OLxHdSdXCPIJg="}}
     *
     * @throws Exception
     */

//    @Value("#{pay_info.address}")
    private String  notifyAddress ="134.175.81.119:8091";//"106.91.7.196:8091";//


    @Autowired
    private RechargeManager rechargeManager;



    public  JSONObject payment(long playerId,int goods,JSONObject businessContext) throws Exception {

        System.out.println("sdf"+notifyAddress);

        JSONObject businessHead = buildBusinessHead();
        System.out.println("{\"businessContext\":" + businessContext + ",\"businessHead\":" + businessHead + "}");
        // 加密请求数据
        String reqEncrypt = RSAUtils.verifyAndEncryptionToString(businessContext, businessHead, PayConfig.MCH_PRIVATE_KEY, PayConfig.SHB_PUBLIC_KEY);
        JSONObject context = new JSONObject();
        context.put("context", reqEncrypt);
        System.out.println(context.toString());
        String respEncrypt = HttpUtils.httpPost(PayConfig.HOST_URL + PayConfig.UNIFIED_PAYMENT_URL, context.toString());
        System.out.println(respEncrypt);
        JSONObject respJson = JSONObject.fromObject(respEncrypt);

        if (respJson.get("success").toString().equals("false")) {
            /*{
                "message" : {
                "code" : 3003,
                "content" : "签名异常"
                },
                "context" : null,
                "success" : false
            }*/
            // 请求失败
            respJson.get("context");
            respJson.get("message");
            return respJson;
        }

        String decrypt = RSAUtils.decryptByPrivateKey(respJson.getString("context"), PayConfig.MCH_PRIVATE_KEY);//商户私钥解密
        JSONObject decryptJson = JSONObject.fromObject(decrypt);//明文数据
//        System.out.println(decryptJson.toString());

        // 验签
        if (!RSAUtils.verify(decrypt, PayConfig.SHB_PUBLIC_KEY)) {
            respJson.put("success","false");
            return respJson;
        }

        JSONObject respHead = decryptJson.getJSONObject("businessHead");
        JSONObject respContext = decryptJson.getJSONObject("businessContext");
//        System.out.println(respHead);
//        System.out.println(respContext);
        String orderNumber = respContext.getString("shbOrderNumber");//速汇宝订单号、

        if(rechargeManager.addRechargeLog(playerId,goods,orderNumber,1)){
            System.out.println("充值记录插入成功");
        }

        return respContext;
    }


    /**
     * 请求头
     *
     * @return
     */
    public  JSONObject buildBusinessHead() {
        JSONObject businessHead = new JSONObject();
        businessHead.put("charset", "00");//字符集 00 : utf-8
        businessHead.put("version", "V1.0.0");//版本号
        businessHead.put("method", "payment");//方法
        businessHead.put("merchantNumber", PayConfig.MERCHANT_NUMBER);//商户号
        businessHead.put("requestTime", getSdfTimes());//请求时间
        businessHead.put("signType", "");//签名类型
        businessHead.put("sign", "");//签名
        return businessHead;
    }

    /**
     * 支付请求内容
     *
     * @return
     */
    public  JSONObject buildBusinessContextFormPay(int shopId,String defrayalType,String commodityBody,String commodityDetail,double  tradeAmount,String terminalIP) {
        JSONObject businessContext = new JSONObject();
        businessContext.put("attach", String.valueOf(shopId));//附加信息 "attach": "",
        businessContext.put("channelMapped", "PAY_SYB");//支付通道标识(必填)    "channelMapped": "SAND_PAY",
        businessContext.put("commodityBody", commodityBody);//商品信息(必填)      "commodityBody": "商品信息",
        businessContext.put("commodityDetail", commodityDetail);//商品详情(必填)    "commodityDetail": "商品详情",
        businessContext.put("currenciesType", "CNY");//币种：人民币(必填)   "currenciesType": "CNY",

        businessContext.put("defrayalType",defrayalType);//支付方式(必填)  "defrayalType": "ALI_NATIVE",
        businessContext.put("merchantOrderNumber", System.currentTimeMillis());//商户订单号(必填),每次交易唯一 "merchantOrderNumber": "dsorderid2018011516",
        businessContext.put("notifyUrl", "http://"+notifyAddress+"/api/notify/shb");//异步通知(必填)   "notifyUrl": "http://192.168.2.185:8080/api/notify/shb",
        businessContext.put("orderTime", getSdfTimes());//订单时间(必填)         "orderTime": "20180116144607",
        businessContext.put("subMerchantNumber", PayConfig.MERCHANT_NUMBER);//商户号(必填)
        businessContext.put("terminalIP", terminalIP);//设备IP(必填)
        businessContext.put("tradeAmount", tradeAmount);//交易金额分(必填)
        businessContext.put("tradeCheckCycle", "T1");//结算周期(必填)
        return businessContext;
    }



    public  String getSdfTimes() {
        return new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
    }

}
